var Promise = require('bluebird');
var _ = require('underscore');
var Model = require('../models/content');
var base = require('./baseService');

//Delete
exports.Delete=function(req){
  return new Promise(function(resolve,reject){
    var delids = [];
    if(req.params.id)
        delids.push(req.param.id);
    else
				if(req.body.ids)
        delids = req.body.ids;
		Model.update({_id:{$in:delids}},{$set:{isdel:true}},{multi:true},function(err,tank){
			if (err) 
        return handleError(err);
			resolve(tank.nModified>0?base.Success("删除成功"):base.Error("删除失败"));
		});
  });
}

//Save
exports.Save=function(req){
  return new Promise(function(resolve, reject){
    var entity = req.body;
    var _entity = new Model(entity);
    _entity.save(function(err){
      if(err){
        reject(base.Error(err));
      }
      else{
        resolve(base.Success("添加成功"))
      }
    });
  });
}
//Update
exports.Update=function(req){
  return new Promise(function(resolve, reject){
    var entity = req.body;
    Model.findById(entity._id,function(err,_entity){
        _entity.title = entity.title;
        _entity.bannerimage = entity.bannerimage;
        _entity.display = entity.display;
        _entity.save(function(err){
          if(err){
            reject(base.Error(err));
          }
          resolve(base.Success("修改成功"))
        });
      });
  });
}
//Get
exports.Get=function(req){
  return new Promise(function(resolve,reject){
    var entityID = req.params.id;
    Model.findById(entityID,function(err,contenttype){
      if(err)
        reject(err);
      else
        resolve(contenttype);
    });
  });
}
//GetList
exports.GetList=function(req){
  return new Promise(function(resolve, reject){
    var pe = base.GetPage(req);
    //添加条件
    var filter = {
      isdel:false
    };
    if(pe.getParam('title')){
      filter.title = new RegExp(pe.getParam('title')+'.*','i')
    }
    Model.find(filter)
    .limit(pe.getLimit())
    .skip(pe.getStartLine())
    .exec(function(err,list){
      if(err)
        reject(err);
      else{
        pe.data = list;
        Model.count(filter).count(function(err,count){
          if(err)
            reject(err)
          else{
            pe.recordsFiltered = count;
            pe.recordsTotal = count;
            resolve(pe);
          }
        })
      }
    });
  });
}